package mes.kanban.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.WebApplicationContextUtils;

import mes.kanban.config.MyShiroRealm;
import mes.kanban.util.DateUtil;
import mes.kanban.vo.MesUserVO;

@Controller
public class LoginController {
	
	
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	// 此方法不处理登录成功,由shiro进行处理
	@RequestMapping("/login")
	public String goToLogin(Model model,HttpServletRequest request) {
		
		log.info("---------------------in login "+DateUtil.getCurrentDate(new Date()));
		
		String exception = (String) request.getAttribute("shiroLoginFailure");
        log.info("exception=" + exception);
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                log.info("UnknownAccountException -- > 账号不存在：");
                msg = "出错啦：账号不存在：";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                log.info("IncorrectCredentialsException -- > 账号or密码不正确：");
                msg = "出错啦：账号or密码不正确：";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                log.info("kaptchaValidateFailed -- > 验证码错误");
                msg = "出错啦：验证码错误";
            } else if(LockedAccountException.class.getName().equals(exception)){
            	log.info("LockedAccountException -- > 账号已禁用");
                msg = "出错啦：账号已禁用";
            }else{
                msg = "其他错误，请联系管理员";
                log.error("else -- >" + exception);
            }
        }else {
        	
        	log.info("执行清数据操作..........................................");
        	
        	MyShiroRealm myShiroRealm = null;
    		
    		BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()); 
    		
    		myShiroRealm = factory.getBean(MyShiroRealm.class);
    		
    		//清除掉当前用户的权限信息
            myShiroRealm.clearAuthz(request);
            
			try {

				HttpSession session = WebUtils.toHttp(request).getSession();
				Object userinfoName = session.getAttribute("userSessionName");

				// 清除掉当前用户的权限信息
				myShiroRealm.clearAuthz(request);

				log.info("成功清除{" + userinfoName + "}权限");
			} catch (Exception e) {
	   			e.printStackTrace();
	   			log.error("数据清除失败:"+e.getMessage());
	   		}
            
        }
		
		model.addAttribute("error_message", msg);
		
		return "login/index";
	}
	
	
	@GetMapping(value="/loginjk/{showR}")
	public String returnLoginIndexForRegist(Model model,@PathVariable String showR) {
		
		model.addAttribute("showR", showR);
		
		return "login/index";
	}
	
	@RequestMapping("/403")
    public String unauthorizedRole(){
        log.info("------没有权限-------");
        return "403";
    }
	
	@RequestMapping({"/","/index",""})
	public String loginSuccessToIndex(HttpServletRequest request) {
		
		log.info("login success to redirect here .......");
		
        //return "redirect:/pollingConfig/list";
		return "redirect:/toDashboard";
		
	}
	
	@RequestMapping("/toDashboard")
	public String toList1(HttpServletRequest request,Model model) {
		
		
		HttpSession session = WebUtils.toHttp(request).getSession();
		
		Object info = session.getAttribute("userSession");
		
		MesUserVO userInfo = new MesUserVO();
		
		BeanUtils.copyProperties(info, userInfo);
		
		userInfo.setPassWord(null);
		
		userInfo.setSalt(null);
		
		model.addAttribute("userInfo", userInfo);
		
        return "dashboard_element";
	}

}
